#include "ftp.h"
#include <openssl/md5.h>
#define READ_DATA_SIZE  1024
#define MD5_SIZE        16
#define MD5_STR_LEN     (MD5_SIZE * 2)

//传入md5字符串数组用于接收生成的码值
//md5码长度共计32位
int getMd5(const char *file_path, char *md5_str)
{
    int i;
    int fd;
    int ret;
    unsigned char data[READ_DATA_SIZE];
    unsigned char md5_value[MD5_SIZE];
    MD5_CTX md5;

    fd = open(file_path, O_RDONLY);
    ERROR_CHECK(fd, -1, "getmd5 open");
    MD5_Init(&md5);
    while (1){
        ret = read(fd, data, READ_DATA_SIZE);
        ERROR_CHECK(ret, -1, "getmd5 read");
        MD5_Update(&md5, data, ret);
        if (0 == ret || ret < READ_DATA_SIZE){
            break;
        }
    }
    close(fd);
    MD5_Final(md5_value, &md5);
    for(i = 0; i < MD5_SIZE; i++){
        snprintf(md5_str + i*2, 2+1, "%02x", md5_value[i]);
    }
    md5_str[MD5_STR_LEN] = '\0';
    return 0;
}
